/*
 * Copyright (c) 2010 CCX(China) Co.,Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * CCX(China) Co.,Ltd. ("Confidential Information").
 * It may not be copied or reproduced in any manner without the express 
 * written permission of CCX(China) Co.,Ltd.
 *
 * @author Administrator
 * Date: 2010-7-6 上午10:22:27
 */
package com.ccxe.manage.service.impl;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ccxe.manage.dao.impl.IM_Menu_Role_DaoImpl;
import com.ccxe.manage.dao.impl.UserRoleDaoImpl;
import com.ccxe.manage.util.StringValueValid;

/**
 * IM_Menu_Role 表 业务类
 * 
 * @author wangyx
 * 
 */
public class IM_Menu_Role_Service extends TransactionService {

	private Map<?, ?> parameterMap;

	private IM_Menu_Role_DaoImpl dao = new IM_Menu_Role_DaoImpl();

	private UserRoleDaoImpl u_r_dao = new UserRoleDaoImpl();

	private static final Logger logger = LoggerFactory.getLogger(IM_Menu_Role_Service.class);
	/**
	 * 批量删除
	 * 
	 * @return
	 * @throws Exception
	 */
	private int deleteByRoleId() throws Exception {
		return tranDb.executeUpdate(dao.getDeleteByRoleIdSql(),
				new String[] { (String) parameterMap.get("roleId") });
	}

	/**
	 * 批量插入
	 * 
	 * @param roleId
	 * @param menuList
	 * @return
	 * @throws Exception
	 */
	private int insertByList() throws Exception {
		int result = 0;
		String roleId = (String) parameterMap.get("roleId");
		String[] menuList = (String[]) parameterMap.get("menuList");
System.out.println("menuList size: "+menuList.length);		
		if (menuList != null && menuList.length > 0
				&& StringValueValid.isNotNullAndEmpty(menuList[0])) {
			for (String str : menuList) {
				System.out.print(" menuId:"+str);
			}
			for (String menuId : menuList) {
				logger.info("SQL : "+dao.getInsertOneSql() +"Values : "+roleId +";"+menuId);
				tranDb.executeUpdate(dao.getInsertOneSql(), new String[] {
						roleId.trim(), menuId.trim() });
				result++;
			}
		}
		return result;
	}

	/**
	 * 事务:向C_Menu_Role插入数据,先删除,后插入
	 * 
	 * @throws Exception
	 */
	@Override
	protected void doTransactionOperate() {
		try {
			// 删除 用户--角色 关系表数据
			u_r_dao.deleteUserRole((String) parameterMap.get("roleId"));
			// 删除 角色--权限 关系表 所有该角色下的数据
			deleteByRoleId();
			// 插入新的数据
			insertByList();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setParameterMap(Map<?, ?> parameterMap) {
		this.parameterMap = parameterMap;
	}

}
